<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class='ssss'>
        <video id="video" autoplay style="background-color: #000;"></video>
        <canvas style="display: none;" id="canvas"></canvas>
        <img id="imgXX" src="" alt="这个是什么">
    </div>
    <button id="btn_snap" onclick="takePhoto()">拍照</button>
</body>
<script>
    const cvs = document.getElementById('canvas')
    const video = document.getElementById('video')
    // 宽度设置400
    cvs.width = cvs.height = video.width = video.height = 400
    const { width, height } = cvs
    const ctx = cvs.getContext('2d')
    // 定义吊起摄像头要用的参数格式固定
    const constraints={
        video:{
            width,
            height
        }
    }
    // 媒体设备获取媒体摄像   stream里面的数据流
    navigator.mediaDevices.getUserMedia(constraints).then(stream=>{
    video.srcObject=stream
    // 等数据流加载好之后就会触发这个事件    一旦触发就使用play方法捕捉到画面
    video.onloadedmetadata=()=> video.play()
    })
    // 实现拍照
    function  takePhoto(){
        // canvas可以直接化video
        ctx.drawImage(video,0,0,width,height)
        // 直接把图片打出来
        document.getElementById('imgXX').src=canvas.toDataURL('image/png')
        console.log( ctx.drawImage(video,0,0,width,height));
        console.log(canvas.toDataURL('image/png'));
    }
</script>

</html>